package com.beisita;

import org.mybatis.spring.annotation.MapperScan;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import java.util.Arrays;

//@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ServletComponentScan(basePackages = {"com.beisita.filter", "com.beisita.servlet"})
@SpringBootApplication
@EnableWebMvc
@EnableScheduling
@MapperScan("com.beisita.dao.mapper")
public class BeisitaWebApplication {

    @Value(value = "${app.redis.host}")
    private String host;
    @Value(value = "${app.redis.port}")
    private String port;

    public static void main(String[] args) {
        SpringApplication.run(BeisitaWebApplication.class, args);
    }

    private static final String redisUrlFormat = "redis://%s:%s";

    @Bean
    public Redisson redisson() {
        Config config = new Config();
        String address = String.format(redisUrlFormat, host, port);
        config.useSingleServer().setAddress(address)
                .setTimeout(1000)
                .setRetryAttempts(3)
                .setRetryInterval(1000)
                .setPingConnectionInterval(1000)//**此项务必设置为redisson解决之前bug的timeout问题关键*****
                .setDatabase(0);
        return (Redisson) Redisson.create(config);
    }

    /**
     * 实现在项目启动后执行的功能
     * 例如服务启动执行，执行加载数据等操作
     *
     * @param ctx 入参
     * @return CommandLineRunner
     */
    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
            System.out.println("Let's inspect the beans provided by Spring Boot:");
            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for (String beanName : beanNames)
                System.out.println(beanName);
        };
    }

    //Tomcat large file upload connection reset
/*    @Bean
    public TomcatServletWebServerFactory tomcatEmbedded() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
                //-1 means unlimited
                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
        });
        return tomcat;
    }*/
}
